//
//  TTViewController.m
//  TT
//
//  Created by lanou3g on 16/3/10.
//  Copyright © 2016年 Super磊. All rights reserved.
//

#import "TTViewController.h"
#import "MyAnnotation.h"
#import "OverlapCollectionViewCell.h"
#import "DetailViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "Person.h"
#import <EaseMob.h>


typedef NS_ENUM(NSInteger, Sex) {
    Male,
    Famale,
    All,
};

@interface TTViewController ()<CLLocationManagerDelegate,MKMapViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,changePic>

///定位管理者
@property(nonatomic, strong)CLLocationManager *mgr;
///位置
@property(nonatomic, strong)CLLocation *currentLocation;
///数组
@property(nonatomic, strong)NSMutableArray *arrayALlData;
///坐标
@property(nonatomic, assign)CLLocationCoordinate2D coor2d;
///筛选出的数组
@property(nonatomic, strong)NSMutableArray *resultArray;
///添加数组
@property(nonatomic, strong)NSMutableArray *agreeArray;
///显示的距离
@property(nonatomic, assign)CGFloat distance;
///显示的性别
@property(nonatomic, strong)NSString *sex;
///显示的年龄
@property(nonatomic, assign)NSInteger firstAge;
@property(nonatomic, assign)NSInteger secondAge;

@end

@implementation TTViewController

- (void)loadView {
    self.ttV = [[TTView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.ttV;
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.view.backgroundColor =[UIColor cyanColor];
    
    self.mgr = [[CLLocationManager alloc] init];
    // 版本判断
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        // 如果授权状态不是在前台使用，则手动更改
        if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
            [self.mgr requestWhenInUseAuthorization];
        }
    }
    self.mgr.delegate = self;
    //设置定位基本参数
    self.mgr.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    self.mgr.distanceFilter = 500;
    [self.mgr startUpdatingLocation];//开启定位
    
//    [self.ttV addSubview:self.ttV.mapV];
    self.ttV.mapV.delegate = self;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.ttV.imageV addGestureRecognizer:tap];
    UITapGestureRecognizer *tapTem = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTemAction)];
    [self.ttV.mapV addGestureRecognizer:tapTem];
    
    [self.ttV.cancel addTarget:self action:@selector(cancelAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.ttV.agree addTarget:self action:@selector(agreeAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.ttV.detail addTarget:self action:@selector(detailAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self setConditions];
    [self setUserDefault];
    [self setData];
}
- (void)setUserDefault {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setValue:self.mobilePhoneNumber forKey:@"mobilePhoneNumber"];
}
#pragma mark 判断距离是否符合条件
- (BOOL )distanceWithMyLocation:(CLLocation *)myLocation OtherLocation:(CLLocation *)otherLocation {
    // 单位：米
    CLLocationDistance distance = [myLocation distanceFromLocation:otherLocation];
    if (distance < self.distance) {
        return YES;
    } else {
        return NO;
    }
}

#pragma mark 获取搜索的条件
- (void)setConditions {
    //需要从本地获取
    self.distance = 10000;
    self.sex = @"男";
    self.firstAge = 16;
    self.secondAge = 28;
}
#pragma mark 登陆环信:
- (void)loginEaseWithNumber:(NSString *)number {
    //    登录
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:number password:[NSString stringWithFormat:@"%@%@",number,number] completion:^(NSDictionary *loginInfo, EMError *error) {
        if (!error && loginInfo) {
            NSLog(@"登录成功");
        }
    } onQueue:nil];
}
#pragma mark 根据条件到leancloud请求数据
- (void)setData {
    //1.上传自己的地理位置
    if (!self.mobilePhoneNumber) {
        AVQuery *ownQuery = [AVQuery queryWithClassName:@"DetailReg"];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        self.mobilePhoneNumber = [user valueForKey:@"mobilePhoneNumber"];
        [self loginEaseWithNumber:self.mobilePhoneNumber];
        [ownQuery whereKey:@"mobilePhoneNumber" equalTo:self.mobilePhoneNumber];
        [ownQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                NSLog(@"%@,%ld",objects,objects.count);
                AVObject *own = objects[0];
                [own setObject:self.currentLocation forKey:@"coor2d"];
                [own saveInBackground];
            } else {
                NSLog(@"Error：%@ %@",error,[error userInfo]);
            }
        }];
    }
    
    
    //2.设置筛选条件
    AVQuery *query = [AVQuery queryWithClassName:@"DetailReg"];
//    if ([self.sex isEqualToString:@"男"] || [self.sex isEqualToString:@"女"]) {
//        [query whereKey:@"userGender" equalTo:self.sex];
//    }
//    [query whereKey:@"userAge" greaterThan:[NSNumber numberWithInteger:self.firstAge]];
//    [query whereKey:@"userAge" lessThanOrEqualTo:[NSNumber numberWithInteger:self.secondAge]];
    //3.请求数据
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {//检索成功
            NSLog(@"检索成功");
            //遍历数组，筛选符合距离条件的
            for (AVObject *other in objects) {
//                if ([self distanceWithMyLocation:self.currentLocation OtherLocation:other[@"coor2d"]]) {//添加
//
                Person *p = [[Person alloc] init];
                NSDictionary *dic = [other dictionaryForObject];
                [p setValuesForKeysWithDictionary:dic];
                    [self.resultArray addObject:p];
//                }
            }
            //4.展示信息
            [self replaceMapWithPhoto];
            
            
            
        } else {//输出错误信息
            NSLog(@"Error：%@ %@",error,[error userInfo]);
        }
    }];
    
}

#pragma mark 三个按钮监听事件
- (void)cancelAction
{
    //浏览完毕，重新请求新数据
    if (self.resultArray.count == 0) {
        return;
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    
    [self.resultArray removeObjectAtIndex:0];
    [self.ttV.collectionV deleteItemsAtIndexPaths:@[indexPath]];
    OverlapCollectionViewCell *cell = (OverlapCollectionViewCell *)[self.ttV.collectionV cellForItemAtIndexPath:indexPath];
    cell.userInteractionEnabled = YES;
}
- (void)agreeAction
{
    if (self.resultArray.count == 0) {
        return;
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    
    [self.agreeArray addObject:self.resultArray[0]];
    [self.resultArray removeObjectAtIndex:0];
    [self.ttV.collectionV deleteItemsAtIndexPaths:@[indexPath]];
    OverlapCollectionViewCell *cell = (OverlapCollectionViewCell *)[self.ttV.collectionV cellForItemAtIndexPath:indexPath];
    cell.userInteractionEnabled = YES;
}

- (void)detailAction {
    DetailViewController *detailVC = [[DetailViewController alloc] init];
//    UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:detailVC];
//    [self presentViewController:na animated:NO completion:nil];
    [self.navigationController pushViewController:detailVC animated:YES];
}
#pragma mark 切换对象代理方法
- (void)changePicWithDirection:(Direction)direction {
    if (direction == Left) {
        [self cancelAction];
    } else {
        [self agreeAction];
    }
}

- (void)setCollection {
    [self.ttV.collectionV registerClass:[OverlapCollectionViewCell class] forCellWithReuseIdentifier:@"over_cell"];
    self.ttV.collectionV.delegate = self;
    self.ttV.collectionV.dataSource = self;
}
#pragma mark collectionView delegate
- (NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.resultArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    OverlapCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"over_cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0
                                           green:arc4random() % 256 / 255.0
                                            blue:arc4random() % 256 / 255.0
                                           alpha:1];
    //初始化时设置是否响应
    if (indexPath.item == 0) {
        cell.userInteractionEnabled = YES;
    } else {
        cell.userInteractionEnabled = NO;
    }
    Person *p = self.resultArray[indexPath.row];
    //设置属性
    cell.delegate = self;
    cell.name_age.text = p.userBirthday;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self detailAction];
}
#pragma mark 设置地图
- (void)setMap {
    self.ttV.mapV.layer.cornerRadius = kMapSize / 2;
    self.ttV.mapV.layer.masksToBounds = YES;
    
    self.ttV.mapV.mapType = MKMapTypeStandard;
    MKCoordinateSpan span = MKCoordinateSpanMake(.12, .12);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.coor2d, span);
    [self.ttV.mapV setRegion:region];
    self.ttV.mapV.scrollEnabled = NO;
    self.ttV.mapV.zoomEnabled = NO;
    self.ttV.mapV.rotateEnabled = NO;
    self.ttV.mapV.pitchEnabled = NO;
    self.ttV.imageV.image = [UIImage imageNamed:@"4.jpg"];
}
#pragma mark 移除地图，展示图片
- (void)replaceMapWithPhoto {
    [self.ttV.mapV removeFromSuperview];
    [self.ttV addSubview:self.ttV.showV];
    [self setCollection];
}

#pragma mark 通过获取设置中的距离查找符合条件的对象
- (void)searchWithDistance:(CLLocation *)otherLocation sex:(Sex )sex {
    CLLocationDistance kilometers = [self.currentLocation distanceFromLocation:otherLocation];
    if (kilometers > self.distance) {
        return;
    }
    // 添加到数组
}

#pragma mark location delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    self.currentLocation = [locations firstObject];
    //获取到当前地理位置
    [self setMap];
    self.coor2d = CLLocationCoordinate2DMake(self.currentLocation.coordinate.latitude, self.currentLocation.coordinate.longitude);
    NSLog(@"%lf,%lf",self.currentLocation.coordinate.latitude, self.currentLocation.coordinate.longitude);
    [self.mgr stopUpdatingLocation];//关闭定位
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    } else if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无返获取位置信息");
    }
}


#pragma mark 点击头像图片的响应事件
- (void)tapAction {
    [UIView animateWithDuration:1 animations:^{
        self.ttV.imageV.transform = CGAffineTransformMakeScale(0.4, 0.4);
        self.ttV.imageV.transform = CGAffineTransformMakeScale(1, 1);
    }];
}
- (void)tapTemAction {
    [self replaceMapWithPhoto];
}

//- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {

    
    
//    MyAnnotation *annotation = [[MyAnnotation alloc] init];
//    annotation.icon = @"4.jpg";
//    annotation.coordinate = userLocation.coordinate;
//    [self.ttV.mapV addAnnotation:annotation];
//}
//- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(MyAnnotation *)annotation {
//    if ([annotation isKindOfClass:[MyAnnotation class]] == NO) {
//        return nil;
//    }
//    
//    MKAnnotationView *view = [mapView dequeueReusableAnnotationViewWithIdentifier:@"cell"];
//    if (view == nil) {
//        view = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"cell"];
//    }
//    view.annotation = annotation;
//    view.image = [UIImage imageNamed:annotation.icon];
//    view.canShowCallout = NO;
//    return view;
//}
//#pragma mark 点击大头针（头像）
//- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
//    [UIView animateWithDuration:5 animations:^{
//        NSLog(@"5");
//        view.transform = CGAffineTransformMakeScale(0.5, 0.5);
//    }];
//    [UIView animateWithDuration:0.5 animations:^{
//        NSLog(@"0.5");
//        view.transform = CGAffineTransformMakeScale(1.5, 1.5);
//        view.transform = CGAffineTransformMakeScale(1, 1);
//    }];
//}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    self.ttV.mapV.delegate = nil;
//    self.mgr.delegate = nil;
//}
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    self.ttV.mapV.delegate = nil;
//    self.mgr.delegate = nil;
//}

#pragma mark 懒加载
- (CLLocationManager *)mgr {
    if (!_mgr) {
        _mgr = [[CLLocationManager alloc] init];
    }
    return _mgr;
}
- (NSMutableArray *)arrayALlData {
    if (!_arrayALlData) {
        _arrayALlData = [NSMutableArray array];
    }
    return _arrayALlData;
}
- (NSMutableArray *)agreeArray {
    if (!_agreeArray) {
        _agreeArray = [NSMutableArray array];
    }
    return _agreeArray;
}
- (NSMutableArray *)resultArray {
    if (!_resultArray) {
        _resultArray = [NSMutableArray array];
    }
    return _resultArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
